package com.wsjc.manager.service.rpc.data.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wsjc.common.core.constants.CommonConst;
import com.wsjc.common.core.id.IdGenerator;
import com.wsjc.common.core.utils.CoodinateCovertor;
import com.wsjc.common.core.utils.DateUtils;
import com.wsjc.common.core.utils.OSSFile;
import com.wsjc.manager.dao.hospitals.WjHospitalDao;
import com.wsjc.manager.dao.sterilization.WjSterilizationDao;
import com.wsjc.manager.dao.syndata.WjSynDataDao;
import com.wsjc.manager.dao.user.WjUserDao;
import com.wsjc.manager.entity.WjHospital;
import com.wsjc.manager.entity.WjSterilization;
import com.wsjc.manager.entity.WjUser;
import com.wsjc.manager.service.rpc.data.WjSynDataService;

@Service
public class WjSynDataServiceImpl implements WjSynDataService {

	private Logger logger = LoggerFactory.getLogger(WjSynDataServiceImpl.class);

	@Autowired
	private IdGenerator idGenerator;

	@Autowired
	private WjUserDao wjUserDaoImpl;

	@Autowired
	private WjHospitalDao wjHospitalDaoImpl;
	
	@Autowired
	private WjSterilizationDao wjSterilizationDaoImpl;

	@Autowired
	private WjSynDataDao wjSynDataDao;

	@Override
	public List<WjUser> queryOldTableUsers(Map<String, Object> params) {
		return wjSynDataDao.queryOldTableUsers(params);
	}

	/**
	 * 同步user 数据
	 * 
	 * @param params
	 */
	@Override
	public void synUser(List<WjUser> users) {

		for (WjUser wjUser : users) {
			wjUser.setId(idGenerator.getUsersId(wjUser.getScope()));
		}
		wjUserDaoImpl.insert(users);

	}

	/**
	 * 获取旧库中所有医院信息
	 */
	@Override
	public List<WjHospital> queryOldTableHospitals(Map<String, Object> params) {

		List<WjHospital> hospitals = new ArrayList<>();

		List<String> strs = wjSynDataDao.queryHospitalXXXXXX();

		// List<String> news = wjSynDataDao.queryAllNewDbRegionId(params) ;
		// CreateTableSql.createSterilizationTableSql(news);

		logger.info("Syn|获取到 old db 中 所有 分表 id 个数 :" + strs.size());

		for (String str : strs) {
			params.put("tableName", str);
			try {
				logger.info("Syn|医院表名{}:", params.get("tableName"));
				List<WjHospital> list = wjSynDataDao.queryOldTableHospitals(params);
				if (null != list) {
					hospitals.addAll(list);
				}
			} catch (Exception e) {
				logger.error("Syn|error info{}", e);
			}
		}

		for (WjHospital hospital : hospitals) {

			String hosType = hospital.getOldId().substring(0, 2);
			if (hosType.equals("YY")) {
				hospital.setIndustryCode("医院");
			} else if (hosType.equals("ZS")) {
				hospital.setIndustryCode("诊所");
			} else {
				hospital.setIndustryCode("其他");
			}
			
			hospital.setId(idGenerator.getHospitalId(hospital.getAreaId(), hosType));
		}

		return hospitals;
	}

	/**
	 * 同步医院信息
	 */
	@Override
	public void synHospital(List<WjHospital> hospitals) {
		for (WjHospital hospital : hospitals) {

			WjUser user = wjSynDataDao.queryUserById(hospital.getUserId());

			if(null != user){
				hospital.setUserId(user.getId());
			}
			// 百度 xy 转 高德 xy
			Map<String, Double> map = CoodinateCovertor.bd_decrypt(Double.valueOf(hospital.getBaiduGpsX()), Double.valueOf(hospital.getBaiduGpsY()));
			hospital.setGaodeGpsX(map.get("lon").toString());
			hospital.setGaodeGpsY(map.get("lat").toString());
		}
		wjHospitalDaoImpl.insert(hospitals);

	}

	/**
	 * 获取旧库中灭菌数据
	 */
	@Override
	public List<WjSterilization> queryOldTableSterilization(Map<String, Object> params) {
		
		List<WjSterilization> sterilizations = new ArrayList<>();

		List<String> strs = wjSynDataDao.querySterilizationXXXXXX();

		logger.info("Syn|获取到 old db 中 所有 分表 id 个数 :" + strs.size());

		for (String str : strs) {
			params.put("tableName", str);
			try {
				List<WjSterilization> list = wjSynDataDao.queryOldTableSterilization(params);
				if (null != list) {
					sterilizations.addAll(list);
				}
			} catch (Exception e) {
				logger.error("Syn|error info{}", e);
			}
		}
		return sterilizations;
	}

	/**
	 * 同步灭菌数据
	 */
	@Override
	public void synSterilization(List<WjSterilization> sterilizations) {
		
		for (WjSterilization sterilization : sterilizations) {
			
			String scope = sterilization.getId().substring(5, 11);
			
			sterilization.setTableName(CommonConst.DATA_TABLE_NAME_STERILIZATION + scope);
			logger.info("灭菌效果|数据同步到db|开始执行.....{}" , sterilization);
			
			wjSterilizationDaoImpl.insert(sterilization) ;
			
		}
	}
	
	
	/**
	 * 将对象保存到本地
	 * 
	 * @param sterilizations
	 * @throws IOException
	 */
	public  void createObj(Object obj, String path) {
		
		try {
			
			logger.error("将对象保存到该地址{} :" , path);
			// 1.创建目标路径
			File file = new File(path);
			// 2.创建流通道
			FileOutputStream fos;
			fos = new FileOutputStream(file);
			// 3.创建对象输出流
			ObjectOutputStream objOP = new ObjectOutputStream(fos);
			// 4.向目标路径文件写入对象
			objOP.writeObject(obj);
			// 5.关闭资源
			objOP.close();
		} catch (Exception e) {
			logger.error("将对象保存到文件异常 :" , e);
		}

	}

	/**
	 * 下载oss 文件到本地
	 */
	@Override
	public void downOssFile(Map<String, String> paths) {

		logger.info("下载文件共 {} 个", paths.size());
		try {
			for (Entry<String, String> pair : paths.entrySet()) {
				String ossPath = pair.getKey();
				String localPath = pair.getValue();
				logger.info("OSS 地址 : {}, Local 地址 : {}", ossPath, localPath);
				OSSFile.DownFile(ossPath, localPath);
			}
		} catch (Exception e) {
			logger.info("OSS 文件下载失败 : ", paths.size());
		}

	}

	/**
	 * 处理并保存灭菌数据到本地
	 */
	@Override
	public void saveSterilizationToLocal(List<WjSterilization> sterilizations) {
		
        List<WjSterilization> newList = new ArrayList<>();
		
		String dataType = "00S" ;
        Map<String, String> paths = new HashMap<>();
		
		final String UPLOAD_PDF_PATH = "resources/pdf/";
		final String UPLOAD_DTB_PATH = "resources/dtb/";
		
		String localPath = "d:data/resources" ;
		String date = DateUtils.getReqDate() ;
		
		for (WjSterilization sterilization : sterilizations) {

			String dtbPath = "" ;
			String pdfPath = "" ;
			
			String ossDtbPath = UPLOAD_DTB_PATH + sterilization.getOldId() + ".dtb";
			String ossPdfPath = UPLOAD_PDF_PATH + sterilization.getOldId() + ".pdf" ;
			
			logger.info("该检测数据无对应医院 : 医院oldId {}" , sterilization.getHospitalId());
			
			WjHospital wjHospital = wjSynDataDao.queryHospitalInfoByOldId(sterilization.getHospitalId());
			
			if(null == wjHospital){
				logger.info("该检测数据无对应医院 : 医院id {}" , sterilization.getHospitalId());
				continue;
			}
			
			String areaId = wjHospital.getAreaId();
			
			sterilization.setHospitalType(wjHospital.getIndustryCode());
			
			sterilization.setDataType("00S");  // 灭菌
			
			sterilization.setAreaId(areaId);
			
			sterilization.setHospitalName(wjHospital.getName());
			
			sterilization.setHospitalId(wjHospital.getId());
			
			sterilization.setDetectionTimestamp(DateUtils.getDateByStr(sterilization.getDetectionTime()).getTime());
			
			String ossDir = "";
			
			String localDir = "" ;
			
			String province_id = areaId.substring(0, 2) ;
			String city_id = areaId.substring(0, 4) ;
			sterilization.setId(idGenerator.getDataId(areaId, dataType));
			if(province_id.equals("11") || province_id.equals("12") ||province_id.equals("31") ||province_id.equals("50") ){
				
				localDir = localPath + "/" + province_id+"0000" + "/" + areaId + "/" + wjHospital.getId() + "/" + date  ;
				
				dtbPath = localDir + ".dtb" ;
				pdfPath = localDir + ".pdf" ;
			    ossDir = CommonConst.DATA_RESOURCES_ + province_id+"0000" + "/" + areaId + "/" + wjHospital.getId() + "/" + date + "/" + sterilization.getId();
			}else{
				
				localDir = localPath + "/" + province_id+"0000" + "/" + city_id+"00" + "/" + areaId + "/" + wjHospital.getId() + "/" + date ;
				
				dtbPath = localDir + "/" + sterilization.getId() + ".dtb" ;
				pdfPath = localDir + "/" + sterilization.getId() + ".pdf" ;
				ossDir = CommonConst.DATA_RESOURCES_ + province_id+"0000" + "/" + city_id + "/" + areaId + "/" + wjHospital.getId() + "/" + date + "/" + sterilization.getId();
			}
			
			sterilization.setOssDir(ossDir);
			
			logger.info("重新封装后的sterilization信息 {}" , sterilization.toString());
			
			// 封装到新的 list 中
			newList.add(sterilization) ;
			
			paths.put(ossDtbPath, dtbPath);
			paths.put(ossPdfPath, pdfPath);
			
			File file = new File(localDir);  
			if(!file.exists()){ 
				logger.info("文件夹 {} 不存在,开始创建它.....", localDir);
			    file.mkdirs();  
			} 
//			break ;
		}
		
		File file = new File(CommonConst.LOCAL_FILE_PATH_DOWN_OSS_FILE);  
		if(!file.exists()){ 
			logger.info("文件夹 {} 不存在,开始创建它.....", CommonConst.LOCAL_FILE_PATH_DOWN_OSS_FILE);
		    file.mkdirs();  
		} 
		
		/** 数据保存到文件 **/
		createObj(paths, CommonConst.LOCAL_FILE_PATH_DOWN_OSS_FILE + "/down-oss-file-path.txt");
		
		file = new File(CommonConst.LOCAL_FILE_PATH_STERILIZATIONS);  
		if(!file.exists()){ 
			logger.info("文件夹 {} 不存在,开始创建它.....", CommonConst.LOCAL_FILE_PATH_STERILIZATIONS);
			file.mkdirs();  
		} 
		/** 数据保存到文件 **/
		createObj(newList, CommonConst.LOCAL_FILE_PATH_STERILIZATIONS + "/sterilizations.txt");
	}
	
	
	
	
	
	
	
	
	
	

}
